package com.buka.book.controller;

import com.buka.book.entity.Book;
import com.buka.book.service.BookService;
import com.buka.common.Result;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/search")
public class SearchServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String idStr = req.getParameter("id");
        int id = Integer.parseInt(idStr);
        Book byId = new BookService().getById(id);

        //ajax发送请求，返回的数据应该是一个json字符串
        PrintWriter writer = resp.getWriter();
        if(null != byId){

            //json 和java map
            //将书籍对象转为json字符串 返回给前台
            //{
            //  "code":200,
            //  "msg":"",
            //  "data":{
            //              "bookName":"西游记",
            //              "count":10,
            //          }
            // }
            writer.write(Result.success(byId));
        }else{
            writer.write(Result.error("数据为空"));
        }
    }
}
